/**
 *   Copyright:  (C) 2022 Quectel
 *               All rights reserved.
 *    Filename:  myapi.c
 * Description:  This is libmyapi source file
 *     Version:  1.0.0
 *      Author:  fulinux(fulinux@sina.com)
 *   ChangeLog:  1, Release initial version on 20220308
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

typedef struct myapi_handle {
    int id;
    int age;
    char name[20];
} myapi_handle_t;

int myapi_init(intptr_t *fd)
{
    int ret = 0;

    myapi_handle_t *p = NULL;

    if (fd == NULL) {
        printf("fd address is NULL\n");
        return -1;
    }

    if (*fd != 0) {
        printf("fd is invalid or busy\n");
        return -2;
    }

    p = (myapi_handle_t *)malloc(sizeof(myapi_handle_t));
    if (p == NULL) {
        printf ("malloc error\n");
        return -3;
    }

    memset(p, 0, sizeof(myapi_handle_t));

    *fd = (intptr_t)p;

    return 0;
}

int myapi_exit(intptr_t *fd)
{
    int ret = 0;

    myapi_handle_t *p = NULL;

    if (fd == NULL) {
        printf("fd address is NULL\n");
        return -1;
    }

    if (*fd == 0) {
        printf("fd is invalid\n");
        return -2;
    }

    p = (myapi_handle_t *)*fd;

    //do some release

    free(p);
    p = NULL;
    *fd = 0;

    return 0;
}

int myapi_get_age(intptr_t *fd, int *age)
{
    int ret = 0;

    myapi_handle_t *p = NULL;

    if (fd == NULL) {
        printf("fd address is NULL\n");
        return -1;
    }

    if (*fd == 0) {
        printf("fd is invalid\n");
        return -2;
    }

    if (age == NULL) {
        printf("age address is NULL\n");
        return -3;
    }

    p = (myapi_handle_t *) *fd;

    *age = p->age;

    return 0;
}

int myapi_set_age(intptr_t *fd, int age)
{
    int ret = 0;

    myapi_handle_t *p = NULL;

    if (fd == NULL) {
        printf("fd address is NULL\n");
        return -1;
    }

    if (*fd == 0) {
        printf("fd is invalid\n");
        return -2;
    }

    p = (myapi_handle_t *) *fd;

    p->age = age;

    return 0;
}
